package com.qianguo.buyer.order;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.icon.FruitIcon;
import com.eva.androidlibrary.utils.IconfontUtil;
import com.eva.androidlibrary.widget.NoScrollListView;
import com.qianguo.buyer.R;
import com.qianguo.buyer.address.BuyerAddressActivity;
import com.qianguo.buyer.base.BaseTitleActivity;
import com.qianguo.buyer.entity.BuyerAddress;
import com.qianguo.buyer.entity.DeliveryTime;
import com.qianguo.buyer.entity.OrderSN;
import com.qianguo.buyer.entity.PayInfo;
import com.qianguo.buyer.entity.PayResult;
import com.qianguo.buyer.entity.ShopCar;
import com.qianguo.buyer.entity.ShopCarItem;
import com.qianguo.buyer.widget.DeliveryTimeDialog;
import com.qianguo.buyer.widget.ListContentDialog;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * @author eva
 * @date 16/8/18
 */
@EActivity(R.layout.activity_order_confirm)
public class BuyerOrderConfirmActivity extends BaseTitleActivity {

    @ViewById(R.id.order_confirm_address_layout)
    RelativeLayout mRlAddress;

    @ViewById(R.id.order_confirm_address_icon_text_view)
    TextView mTvAddressIcon;

    @ViewById(R.id.order_confirm_address_type_text_view)
    TextView mTvAddressType;

    @ViewById(R.id.order_confirm_address_text_view)
    TextView mTvAddress;

    @ViewById(R.id.confirm_order_delivery_time_text_view)
    TextView mTvDeliveryTime;

    @ViewById(R.id.confirm_order_coupons_text_view)
    TextView mTvCoupons; //优惠券

    @ViewById(R.id.confirm_order_price_text_view)
    TextView mTvProductTotalPrice; // 商品总价

    @ViewById(R.id.confirm_order_delivery_price_text_view)
    TextView mTvDeliveryPrice; // 配送费

    @ViewById(R.id.confirm_order_discount_amount_text_view)
    TextView mTvDiscountAccounts; // 优惠金额

    @ViewById(R.id.confirm_order_total_price_text_view)
    TextView mTvTotalPrice; // 总计

    @ViewById(R.id.confirm_order_pay_wechat_icon_text_view)
    TextView mIconWechat;

    @ViewById(R.id.confirm_order_pay_wechat_choose_text_view)
    TextView mIconWechatChoose;

    @ViewById(R.id.confirm_order_pay_wechat_text_view)
    TextView mTvWechat;

    @ViewById(R.id.confirm_order_pay_ali_icon_text_view)
    TextView mIconAliPay;

    @ViewById(R.id.confirm_order_pay_ali_choose_text_view)
    TextView mIconAliChoose;

    @ViewById(R.id.confirm_order_pay_ali_text_view)
    TextView mTvAliPay;

    @ViewById(R.id.confirm_order_product_list_view)
    NoScrollListView mProductListView;

    @ViewById(R.id.buyer_shop_cart_action_text_view)
    TextView mTvPay;

    @ViewById(R.id.buyer_shop_cart_total_price_text_view)
    TextView mTvPayPrice;

    @ViewById(R.id.buyer_shop_cart_layout)
    RelativeLayout mRlPay;

    @Extra("shopId")
    String mShopID;

    private BuyerAddress mAddress;
    private ShopCar mShopCart;

    private DeliveryTime mDeliveryTimeData;//api获取的配送时间参数
    private List<String> mDeliveryDay;
    private int mDayKey;
    private String mDay, mTimeKey;

    private static final int PAY_TYPE_ALI = 0;
    private int PAY_TYPE = PAY_TYPE_ALI;
    private String mShopCartID = "";

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BuyerAddress address) {
        this.mAddress = address;
        mTvAddressType.setText("[" + BuyerAddress.AddressType.get(address.getAddType()).toString() + "]");
        mTvAddress.setText(address.getAddress() + "\n" + address.getReceiver() + "  " + address.getMobile());
    }

    public static void jumpToConfirmOrder(Context context, String shopId) {
        Intent intent = new Intent();
        intent.putExtra("shopId", shopId);
        intent.setClass(context, BuyerOrderConfirmActivity_.class);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.confirm_order);
    }

    @Override
    protected void initializeUI() {
        chooseWechat();
        mRlPay.setVisibility(View.VISIBLE);
        mTvPay.setText(getString(R.string.buyer_order_detail_pay));
        EventBus.getDefault().register(this);
        IconfontUtil.setIcon(this, mTvAddressIcon, FruitIcon.ICON_LOCATION);
        getShopCart();
        getDeliveryTimeData();
    }

    // 选择收货地址
    @Click(R.id.order_confirm_address_layout)
    void clickChooseAddress() {
        BuyerAddressActivity.jumpToChooseAddress(this);
    }

    // 选择配送时间
    @Click(R.id.confirm_order_choose_delivery_time_layout)
    void clickChooseDeliveryTime() {
        showDatePicker();
    }

    // 选择微信支付
    @Click(R.id.confirm_order_pay_wechat_icon_text_view)
    void clickWechat() {
        chooseWechat();
    }

    @Click(R.id.confirm_order_pay_ali_icon_text_view)
    void clickAli() {
        chooseAli();
    }

    // 去支付
    @Click(R.id.buyer_shop_cart_settle_accounts_layout)
    void clickPay() {
        confirmOrder();
    }

    @Background
    void confirmOrder() {
        mApp.getApi().confirmShopCarOrder(mApp.getUser().getToken(), mShopCartID, mAddress.getReceiver(),
                mAddress.getMobile(), mAddress.getAddress(), mTimeKey, "0", new HttpRequestCallback<OrderSN>() {
                    @Override
                    public void onSuccess(int code, String msg, OrderSN data) {
                        getPayInfo(data.getOrdersn());
                    }

                    @Override
                    public void onFailure(int code, String msg) {

                    }
                });
    }

    void getPayInfo(String orderSN) {
        mApp.getApi().payOrder(mApp.getUser().getToken(), orderSN, 2, new HttpRequestCallback<PayInfo>() {
            @Override
            public void onSuccess(int code, String msg, PayInfo data) {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(BuyerOrderConfirmActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data.getOrderStr(), true);
                handleAliPayResult(result);
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    @UiThread
    void handleAliPayResult(String result) {
        PayResult payResult = new PayResult(result);
        /**
         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
         * docType=1) 建议商户依赖异步通知
         */
        String resultInfo = payResult.getResult();// 同步返回需要验证的信息

        String resultStatus = payResult.getResultStatus();
        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {
            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
        } else {
            // 判断resultStatus 为非"9000"则代表可能支付失败
            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            if (TextUtils.equals(resultStatus, "8000")) {
                Toast.makeText(this, "支付结果确认中", Toast.LENGTH_SHORT).show();

            } else {
                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();

            }
        }
    }

    /**
     * 获得下单时间数据
     */
    @Background
    void getDeliveryTimeData() {
        showLoadingDialog(this);
        mApp.getApi().getDeliveryTimeData(new HttpRequestCallback<DeliveryTime>() {
            @Override
            public void onSuccess(int code, String msg, DeliveryTime data) {
                mDeliveryTimeData = data;
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(BuyerOrderConfirmActivity.this, msg);
            }
        });
        closeLoadingDialog();
    }

    @Background
    void getShopCart() {
        mApp.getApi().getShopCarList(mApp.getUser().getToken(), mShopID, new HttpRequestCallback<ShopCar>() {
            @Override
            public void onSuccess(int code, String msg, ShopCar data) {
                mShopCart = data;
                refreshUI();
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(BuyerOrderConfirmActivity.this, msg);
            }
        });
    }

    @UiThread
    void refreshUI() {
        mTvProductTotalPrice.setText("￥" + mShopCart.getTotal_price());
        mTvDeliveryPrice.setText("￥0");
        mTvDiscountAccounts.setText("- ￥0");
        mTvTotalPrice.setText("￥" + mShopCart.getTotal_price());
        mTvPayPrice.setText("付款￥" + mShopCart.getTotal_price());

        ProductListAdapter adapter = new ProductListAdapter(this);
        mProductListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void showDatePicker() {
        new DeliveryTimeDialog.Builder(BuyerOrderConfirmActivity.this)
                .setTimeType(DeliveryTimeDialog.TIME_DAY)
                .title(getResources().getString(R.string.choose_delivery_data))
                .setListCallback(new ListContentDialog.ListCallback() {
                    @Override
                    public void onSelection(int position, String val) {
                        mDay = val;
                        mDayKey = position;
                        showTimePicker();
                    }
                }).show();
    }

    private void showTimePicker() {
        new DeliveryTimeDialog.Builder(BuyerOrderConfirmActivity.this)
                .setTimeType(DeliveryTimeDialog.TIME_HOUR)
                .setDeliveryTimeData(mDeliveryTimeData)
                .setTimeDataClickListener(new DeliveryTimeDialog.TimeDataClickCallback() {
                    @Override
                    public void onSelection(int position, String str, String val) {
                        mTimeKey = val;
                        mTvDeliveryTime.setText("预计" + mDay + " " + str + "送达");

                    }
                })
                .setDayKey(mDayKey)
                .title(getResources().getString(R.string.choose_delivery_time))
                .content(mDeliveryDay).show();
    }

    private void chooseWechat() {
        IconfontUtil.setIcon(this, mIconWechat, FruitIcon.ICON_WECHAT_SELECTED);
        IconfontUtil.setIcon(this, mIconAliPay, FruitIcon.ICON_ALI_PAY);
        mTvWechat.setTextColor(getResources().getColor(R.color.wechat));
        mTvAliPay.setTextColor(getResources().getColor(R.color.secondary_text_color));
        mIconWechatChoose.setVisibility(View.VISIBLE);
        mIconAliChoose.setVisibility(View.GONE);
    }

    private void chooseAli() {
        IconfontUtil.setIcon(this, mIconWechat, FruitIcon.ICON_WECHAT);
        IconfontUtil.setIcon(this, mIconAliPay, FruitIcon.ICON_ALI_PAY_SELECTED);
        mTvWechat.setTextColor(getResources().getColor(R.color.secondary_text_color));
        mTvAliPay.setTextColor(getResources().getColor(R.color.ali));
        mIconWechatChoose.setVisibility(View.GONE);
        mIconAliChoose.setVisibility(View.VISIBLE);
    }


    private class ProductListAdapter extends BaseAdapter {

        private Context context;

        public ProductListAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return mShopCart.getGoods() != null ? mShopCart.getGoods().size() : 0;
        }

        @Override
        public ShopCarItem getItem(int position) {
            return mShopCart.getGoods().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_confirm_order_product, null);
            }
            ImageView cover = (ImageView) convertView.findViewById(R.id.item_confirm_order_product_cover_image_view);
            TextView name = (TextView) convertView.findViewById(R.id.item_confirm_order_product_name_text_view);
            TextView price = (TextView) convertView.findViewById(R.id.item_confirm_order_product_price_text_view);
            TextView num = (TextView) convertView.findViewById(R.id.item_confirm_order_product_num_text_view);

            final ShopCarItem item = getItem(position);
            mImageLoader.loadImage(context, cover, item.getImg_url());
            name.setText(item.getName());
            price.setText("￥" + item.getPrice());
            num.setText("x" + item.getNum());

            mShopCartID += item.getCartid() + ",";
            return convertView;
        }
    }

}
